var map = null;
var map2 = null;
var printMap = null;
var directionsError = false;
var mapOptions;
var cityName;
var countryCode;
var start;
var end;
var handlerFail;
var handlerSuccess;
var searchingComplete = false;
var directionsManager;
var directionsManager2;
var directionsManager3;
var apiDisabled = false;

function createMapBoxMap(lat, lng, zoom) {
	L.mapbox.accessToken = MAPBOX_KEY;  
    map = L.mapbox.map('map').setView([lat, lng], zoom);
    var styleLayer = L.mapbox.styleLayer('mapbox://styles/mapbox/streets-v9').addTo(map);
    apiDisabled = true;
    $('#map').addClass('show-map');
}

function invalidateKey() {
	$.ajax({
		url:AJAX_URL,
		data: {
			action:'disable_bing_key',
			key:Lander.BING_KEY
		}
	});
}

function countKeyUssage() {
	$.ajax({
		url:AJAX_URL,
		data: {
			action:'count_bing_key',
			key:Lander.BING_KEY
		}
	});
}

function validateBingKey(lat, lng, zoom) {
	$.ajax({
        url: "http://dev.virtualearth.net/REST/v1/Locations",
        dataType: "jsonp",
        data: {
            key: Lander.BING_KEY,
            q: 'New York'
        },
        jsonp: "jsonp",
        success: function (data) {
        	if(data.errorDetails && data.errorDetails.length > 0) {
        		createMapBoxMap(lat, lng, zoom);
        		invalidateKey();
        	} else {
        		countKeyUssage();
        	}
        }
    });
}

function createMap(lat, lng, zoom) {
	try {
		mapOptions = {
		    credentials: Lander.BING_KEY,
		    center:new Microsoft.Maps.Location(lat, lng),
	        zoom: zoom,
	        backgroundColor:'#fff'
	    };

    	map = new Microsoft.Maps.Map('#map', mapOptions);
    	
    	Microsoft.Maps.Events.addHandler(map, '_mapLoaded', function(e) {
			$('#map').addClass('show-map');
		});

		validateBingKey(lat, lng, zoom);

	} catch(e) {
		createMapBoxMap(lat, lng, zoom);
	}
}

function initializeMap() {
    $("#map").html('');
    $("#map2").html('');
    $("#print-map").html('');

    if(Lander.latitude == '40.4019894') {
        createMap(Lander.latitude, Lander.longitude, 5);
    } else {
        createMap(Lander.latitude, Lander.longitude, 12);
    }

    setAutoCompletePlaces();
}

function initPrintMap() {
	var hasPrintMap = false;
	try {
	 	var currentPrint = directionsManager3.getRouteResult();
	 	hasPrintMap = true;
	}
	catch(err) {
	 	hasPrintMap = false;
	}
	if(!currentPrint){
 		directionsManager3.calculateDirections();
	}
}

function setOfferMap(){
  	
}

function successOkMessage(response){
	searchingComplete = true;
    directionsError = false;

	$('#modal-directions h2').hide();
    $('#modal-directions h2.js-success-ok').show();

    $('#directions-holder').show();
    $('#directions-error').hide();
    $('.directions-routes').hide();

}

function errorMessage(error){
	searchingComplete = true;
    directionsError = true;

	$('#modal-directions h2').hide();
    $('#modal-directions h2.js-success-no').show();

    $('#directions-holder').hide();
    $('#directions-error').show();
    $('.directions-routes').hide();
}

function finalPopupShownCallback() {
    // if($('#map-preview').length === 0)
    //     return;
    
    // var preview_map = new google.maps.Map(document.getElementById('map-preview'), {
    //     zoom: Lander.mapZoom,
    //     scrollwheel: false,
    //     navigationControl: true,
    //     mapTypeControl: false,
    //     scaleControl: true,
    //     draggable: true,
    //     center: preview_location
    //  });
}

function calculatingRoute(geoip){
	if(apiDisabled) {
		errorMessage();
		return;
	}

    $('#directions-holder').html('');
    $('#direction-content').html('');
    $('#print-directions').html('');
	
	var fail1 = function() {
       errorMessage();
    };

    map2 = new Microsoft.Maps.Map('#map2', mapOptions);
    printMap = new Microsoft.Maps.Map('#print-map', mapOptions);

    var fail2 = function() {
        start = cityName + ', ' + countryCode;
        end = document.getElementById("js-starting-location").value;

        routeRequest(fail3);
    }

    var fail3 = function() {
        start = cityName + ', ' + countryCode;
        end = document.getElementById("js-destination").value;

        routeRequest(fail1);
    }

	if(!geoip) {
        start = document.getElementById("js-starting-location").value;
        end = document.getElementById("js-destination").value;
        routeRequest(fail2);
    } else {
        start = cityName + ', ' + countryCode;
        end = document.getElementById("js-destination-geoip").value;
        routeRequest(fail1);
    }
}

function routeRequest(fail) {	
	$('.js-print-from').text(start);
    $('.js-print-to').text(end);

	Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: function(){

		// Initialize the DirectionsManager
		directionsManager  = new Microsoft.Maps.Directions.DirectionsManager(map2);
		directionsManager2 = new Microsoft.Maps.Directions.DirectionsManager(map2);
		directionsManager3 = new Microsoft.Maps.Directions.DirectionsManager(printMap);

		 // Create start and end waypoints
		var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:start});
		var endWaypoint = new Microsoft.Maps.Directions.Waypoint({address:end});
		
		// add waypoints
		directionsManager.addWaypoint(startWaypoint);
		directionsManager.addWaypoint(endWaypoint);
		// add waypoints
		directionsManager2.addWaypoint(startWaypoint);
		directionsManager2.addWaypoint(endWaypoint);
		// add waypoints
		directionsManager3.addWaypoint(startWaypoint);
		directionsManager3.addWaypoint(endWaypoint);
		
		// Set the id of the div to use to display the directions
		directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directions-holder') });
		// Set the id of the div to use to display the directions
		directionsManager2.setRenderOptions({ itineraryContainer: document.getElementById('direction-content') });
		// Set the id of the div to use to display the directions
		directionsManager3.setRenderOptions({ itineraryContainer: document.getElementById('print-directions') });

	    // reset handler
		Microsoft.Maps.Events.removeHandler(handlerFail);
	    // Specify a handler for when an error occurs
		handlerFail = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', fail);
	   
	   // reset handler
		Microsoft.Maps.Events.removeHandler(handlerSuccess);
	    // Specify a handler for when directions found
		handlerSuccess = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', successOkMessage);
		
		// Calculate directions, which displays a route on the map
		directionsManager2.calculateDirections();
		directionsManager.calculateDirections();
	}});
}

window.onload = function(){
	setAutoCompletePlaces();
    initializeMap();
}